package fragment;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import model.AddressModel;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import sortlist.ItemListActivity;
import global.Global;
import global.Helper;

import com.baidu.platform.comapi.map.l;
import com.example.andoridclient.MainActivity;
import com.example.andoridclient.R;
import com.example.andoridclient.R.id;

import android.R.integer;
import android.R.string;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.ImageColumns;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class CreateOrderFragment extends Fragment implements OnClickListener,
		OnLongClickListener, OnFocusChangeListener {
	private static final int SELECT_FAILURE = -99;
	private static final int LOADING = -1;
	private static final int UNLOADING = -2;
	private static final int GETPHOTO = 1;
	private static final int GETADDRESS = 2;
	private static final int GETRECIEVER = 3;
	private static final int SUCCESS = 4;
	private static final int UPLOADING = 5;
	private static final int SUBMIT_ORDER = 6;
	View view;

	EditText departure;
	EditText addressname;
	EditText defaultaddress;
	EditText expecttime;
	EditText reciever;
	EditText description;

	Button createorder;
	Button upload;

	TextView departureWarn;
	TextView addressnameWarn;
	TextView expecttimeWarn;
	TextView defaultaddressWarn;
	TextView recieverWarn;
	TextView descriptionWarn;

	ProgressDialog progressDialog;

	LinearLayout rl;

	// 收货人sortlist参数
	HashMap<Integer, String> recievermap = new HashMap<Integer, String>();
	// 收货地关联
	List<AddressModel> address = new ArrayList<AddressModel>();
	// 图片位置
	HashMap<Integer, String> urls = new HashMap<Integer, String>();
	// 收货人id
	int chosenreciecer;
	// 上传图片用
	String path = "";
	int indexphoto;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater
				.inflate(R.layout.fragment_creat_order, container, false);

		if (view != null) {

			departure = (EditText) (view.findViewById(R.id.editTextDeparture));
			addressname = (EditText) (view
					.findViewById(R.id.editTextAddressName));
			defaultaddress = (EditText) (view
					.findViewById(R.id.editTextDefaultAddress));
			expecttime = (EditText) (view.findViewById(R.id.editTextExpectTime));
			reciever = (EditText) (view.findViewById(R.id.editTextReciever));
			description = (EditText) (view
					.findViewById(R.id.editTextDescription));

			createorder = (Button) (view.findViewById(R.id.buttonCreateOrder));
			upload = (Button) (view.findViewById(R.id.buttonupload));

			departureWarn = (TextView) (view
					.findViewById(id.textViewDepartureWarn));
			addressnameWarn = (TextView) (view
					.findViewById(id.TextViewAddressNameWarn));
			expecttimeWarn = (TextView) (view
					.findViewById(id.TextViewExpectTimeWarn));
			defaultaddressWarn = (TextView) (view
					.findViewById(id.TextViewDefaultAddressWarn));
			recieverWarn = (TextView) (view
					.findViewById(id.TextViewRecieverWarn));
			descriptionWarn = (TextView) (view
					.findViewById(id.TextViewDescriptionWarn));

			rl = (LinearLayout) (view.findViewById(id.gallery));

			upload.setOnClickListener(this);
			addressname.setOnClickListener(this);
			reciever.setOnClickListener(this);
			createorder.setOnClickListener(this);
		}
		return view;
	}

	// 获取地址列表
	Runnable getaddress = new Runnable() {
		@Override
		public void run() {
			handler.sendEmptyMessage(LOADING);
			String resultAddress = Global.Get("Order/GetAddressList");
			try {
				JSONArray jsonArray = new JSONArray(resultAddress);
				// 解析JSON
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject object = (JSONObject) jsonArray.get(i);
					AddressModel am = new AddressModel();

					am.ID = object.getInt("ID");
					am.SendOutID = object.getInt("SendOutID");
					am.DefaultAddress = object.getString("DefaultAddress");
					am.AddressName = object.getString("AddressName");

					address.add(am);
				}

				// 加入HashMap
				HashMap<Integer, String> map = new HashMap<Integer, String>();
				for (AddressModel addressModel : address) {
					map.put(addressModel.ID, addressModel.AddressName);
				}
				// 开始新activity
				Intent intent = new Intent(getActivity(),
						ItemListActivity.class);
				intent.putExtra("para", map);
				startActivityForResult(intent, GETADDRESS);
			} catch (JSONException e) {
				Message message = new Message();
				message.obj = resultAddress;
				handler.sendMessage(message);
			} finally {
				handler.sendEmptyMessage(UNLOADING);
			}
		}
	};

	// 获取收货人列表
	Runnable getreciever = new Runnable() {
		@Override
		public void run() {
			handler.sendEmptyMessage(LOADING);
			String resultAddress = Global.Get("User/GetRecieverDictionary");
			try {
				JSONArray jsonArray = new JSONArray(resultAddress);
				// 解析JSON
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject object = (JSONObject) jsonArray.get(i);
					recievermap.put(object.getInt("ID"),
							object.getString("RealName"));
				}

				// 开始新activity
				Intent intent = new Intent(getActivity(),
						ItemListActivity.class);
				intent.putExtra("para", recievermap);
				startActivityForResult(intent, GETRECIEVER);
			} catch (JSONException e) {
				Message message = new Message();
				message.obj = resultAddress;
				handler.sendMessage(message);
			} finally {
				handler.sendEmptyMessage(UNLOADING);
			}
		}
	};

	// 上传订单
	Runnable create = new Runnable() {
		@Override
		public void run() {
			handler.sendEmptyMessage(LOADING);
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			list.add(new BasicNameValuePair("Destination", addressname
					.getText().toString()));
			list.add(new BasicNameValuePair("SendOutuserID", String
					.valueOf(Global.user.ID)));
			list.add(new BasicNameValuePair("RecieverID", String
					.valueOf(chosenreciecer)));
			list.add(new BasicNameValuePair("ExpectDate", expecttime.getText()
					.toString()));
			list.add(new BasicNameValuePair("Departure", departure.getText()
					.toString()));
			list.add(new BasicNameValuePair("Description", description
					.getText().toString()));
			list.add(new BasicNameValuePair("Address", defaultaddress.getText()
					.toString()));

			// 上传图片
			indexphoto = 0;
			for (Map.Entry<Integer, String> s : urls.entrySet()) {
				indexphoto++;
				handler.sendEmptyMessage(UPLOADING);
				// 成功
				String result = Global.UploadPost("File/Upload", s.getValue()).replace("\"", "");
				if (result.length() >= 15 && result.charAt(14) == '_') {
					path += result + ",";
				}
				// 失败
				else {
					handler.sendEmptyMessage(UNLOADING);
					Message message = new Message();
					message.obj = result;
					handler.sendMessage(message);
					return;
				}
			}
			list.add(new BasicNameValuePair("Path", path));
			// 提交订单
			String resultOrder = Global.POST("Order/CreateOrder", list);
			try {
				JSONObject object = new JSONObject(resultOrder);
				if (object.has("error")) {
					// 失败
					if (!TextUtils.isEmpty(object.get("error").toString())) {
						Message message = new Message();
						message.obj = object.get("error");
						handler.sendMessage(message);
					}
					// 成功
					else {
						handler.sendEmptyMessage(SUCCESS);
					}
				}

			} catch (JSONException e) {
				Message message = new Message();
				message.obj = resultOrder;
				handler.sendMessage(message);
			} finally {
				handler.sendEmptyMessage(UNLOADING);
			}
		}
	};

	// UI Handler
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case LOADING:
				progressDialog = ProgressDialog.show(getActivity(), "请稍等...",
						"读取中...", true);
				break;
			case UNLOADING:
				if (progressDialog != null) {
					progressDialog.dismiss();
				}
				break;
			case SUCCESS:
				new AlertDialog.Builder(getActivity()).setTitle("提示")
						.setMessage("下单成功！").setIcon(R.drawable.ic_launcher)
						.setPositiveButton("确定", null).create().show();

				MainActivity mainActivity = (MainActivity) getActivity();
				mainActivity.switchContent(mainActivity.orderfragment);
				mainActivity.creatorderfragment = null;
				new Thread(mainActivity.orderfragment.init).start();
				break;
			case UPLOADING:
				if (progressDialog != null) {
					progressDialog.setMessage("正在上传第" + indexphoto + "张图片");
				}
				break;
			case SUBMIT_ORDER:
				if (progressDialog != null) {
					progressDialog.setMessage("正在提交订单");
				}
				break;
			// 其他异常
			default:
				new AlertDialog.Builder(getActivity()).setTitle("提示")
						.setMessage(msg.obj.toString())
						.setIcon(R.drawable.ic_launcher)
						.setPositiveButton("确定", null).create().show();
				break;
			}
		}

	};

	// 点击
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// 选择目的地
		case id.editTextAddressName:
			new Thread(getaddress).start();
			break;
		case id.editTextReciever:
			new Thread(getreciever).start();
			break;
		// 创建订单
		case id.buttonCreateOrder:
			if (!Check()) {
				return;
			}
			new Thread(create).start();
			;
			break;
		case id.buttonupload:
			Intent intent = new Intent();
			/* 开启Pictures画面Type设定为image */
			intent.setType("image/*");
			/* 使用Intent.ACTION_GET_CONTENT这个Action */
			intent.setAction(Intent.ACTION_GET_CONTENT);
			/* 取得相片后返回本画面 */
			startActivityForResult(intent, GETPHOTO);
			break;
		default:
			break;
		}
	}

	@Override
	public boolean onLongClick(View v) {
		ImageView imageView = (ImageView) v;
		rl.removeView(imageView);
		urls.remove(imageView.getId());
		upload.setEnabled(true);
		return true;
	}

	// 弹窗返回值
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		// 添加图片
		case GETPHOTO:
			if (resultCode == -1) {
				Uri selectedImage = data.getData();
				String path= Helper.getPath(getActivity(), selectedImage);
				if (urls.values().contains(path)) {
					return;
				}
				RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(
						100, 100);
				ImageView imageView = new ImageView(getActivity());
				imageView.setImageURI(selectedImage);
				imageView.setOnLongClickListener(this);
				rl.addView(imageView, lp1);
				urls.put(imageView.getId(),path);
				if (urls.size() >= 5) {
					upload.setEnabled(false);
				}
			}
			break;
		case GETADDRESS:
			if (resultCode == -1) {
				int id = data.getIntExtra("id", SELECT_FAILURE);
				if (id != SELECT_FAILURE) {
					for (AddressModel addressModel : address) {
						if (id == addressModel.ID) {
							addressname.setText(addressModel.AddressName);
							defaultaddress.setText(addressModel.DefaultAddress);
							break;
						}
					}
				}
			}
			break;
		case GETRECIEVER:
			if (resultCode == -1) {
				int id = data.getIntExtra("id", SELECT_FAILURE);
				if (id != SELECT_FAILURE) {
					chosenreciecer = id;
					reciever.setText(recievermap.get(id));
				}
			}
			break;
		default:
			break;
		}

	}

	@Override
	public void onFocusChange(View v, boolean isfocus) {
		if (!isfocus) {
			switch (v.getId()) {
			case R.id.editTextDeparture:
				if (departure.getText().toString().contains("'")) {
					departureWarn.setText("发货地不能包含'");
				} else {
					departureWarn.setText("");
				}
				break;
			case R.id.editTextDescription:
				if (description.getText().toString().contains("'")) {
					description.setText("货物内容不能包含'");
				} else {
					description.setText("");
				}
				break;
			default:
				break;
			}
		}
	}

	private boolean Check() {
		boolean flag = true;
		// 检查发货地
		if (TextUtils.isEmpty(departure.getText())) {
			departureWarn.setText("发货地不能为空");
			flag = false;
		}
		if (!TextUtils.isEmpty(departureWarn.getText())) {
			flag = false;
		}
		// 检查收货地
		if (TextUtils.isEmpty(addressname.getText())) {
			addressnameWarn.setText("收货地不能为空");
			flag = false;
		}
		if (!TextUtils.isEmpty(addressnameWarn.getText())) {
			flag = false;
		}
		// 检查收货地地址
		if (TextUtils.isEmpty(defaultaddress.getText())) {
			defaultaddressWarn.setText("收货地地址不能为空");
			flag = false;
		}
		if (!TextUtils.isEmpty(defaultaddressWarn.getText())) {
			flag = false;
		}
		// 检查期望送达时间
		if (TextUtils.isEmpty(expecttime.getText())) {
			expecttimeWarn.setText("期望送达时间不能为空");
			flag = false;
		}
		if (!TextUtils.isEmpty(expecttimeWarn.getText())) {
			flag = false;
		}
		// 检查收货人
		if (TextUtils.isEmpty(reciever.getText())) {
			recieverWarn.setText("收货人不能为空");
			flag = false;
		}
		if (!TextUtils.isEmpty(recieverWarn.getText())) {
			flag = false;
		}
		// 检查货物内容
		if (TextUtils.isEmpty(description.getText())) {
			descriptionWarn.setText("货物内容不能为空");
			flag = false;
		}
		if (!TextUtils.isEmpty(descriptionWarn.getText())) {
			flag = false;
		}
		return flag;
	}
}